package org.javaymw.springboot.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.javaymw.springboot.dto.MenuDto;
import org.javaymw.springboot.dto.RoleMenuDto;
import org.javaymw.springboot.entity.MenuEntity;
import org.javaymw.springboot.entity.RoleMenuEntity;
import org.javaymw.springboot.mapper.MenuMapper;
import org.javaymw.springboot.mapper.RoleMenuMapper;
import org.javaymw.springboot.service.RoleMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/26 19:01
 * @Description:
 */
@Service
@Transactional
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenuEntity> implements RoleMenuService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public void deleteRoleMenuByRoleId(Long roleId) {
        Wrapper<RoleMenuEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        List<RoleMenuEntity> roleMenuEntities = roleMenuMapper.selectList(wrapper);
        if (!roleMenuEntities.isEmpty()) {
            List<Long> roleMenuIds = new ArrayList<>(roleMenuEntities.size());
            roleMenuEntities.stream().forEach(roleMenuEntity -> roleMenuIds.add(roleMenuEntity.getId()));
            roleMenuMapper.deleteBatchIds(roleMenuIds);
        }
    }

    @Override
    public Integer save(RoleMenuDto roleMenuDto) {
        RoleMenuEntity roleMenuEntity = new RoleMenuEntity();
        BeanUtils.copyProperties(roleMenuDto, roleMenuEntity);
        return roleMenuMapper.insert(roleMenuEntity);
    }

    @Override
    public Integer getRoleIdsByRoleId(Long roleId) {
        Wrapper<RoleMenuEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("role_id", roleId);
        return roleMenuMapper.selectCount(wrapper);
    }

    @Override
    public List<MenuDto> getMenusByRoleId(Long roleId) {
        List<MenuEntity> menuEntities = roleMenuMapper.getMenusByRoleId(roleId);
        if (menuEntities == null) return null;
        List<MenuDto> menuDtos = new ArrayList<>();
        menuEntities.stream().forEach(menuEntity -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(menuEntity, menuDto);
            menuDtos.add(menuDto);
        });
        return menuDtos;
    }

}
